<?php
require 'config.php';

class Database {
    private $pdo;

    public function __construct() {
        // 连接数据库
        try {
            $this->pdo = new PDO("mysql:host=$databaseHost;dbname=ywd", "root", "123456");
            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) {
            die("数据库连接失败: " . $e->getMessage());
        }
    }
    public function loginUser($username, $password) {
        try {
            $query = "SELECT * FROM users WHERE username = :username AND password = :password";
            $stmt = $this->pdo->prepare($query);
            $stmt->bindParam(':username', $username);
            $stmt->bindParam(':password', $password);
            $stmt->execute();
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
            if ($user) {
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['avatar_url'] = $user['avatar_url'];
    
                $updateLastLoginQuery = "UPDATE users SET last_login_at = NOW() WHERE id = :id";
                $stmt = $this->pdo->prepare($updateLastLoginQuery);
                $stmt->bindParam(':id', $user['id']);
                $stmt->execute();
    
                return true; // 登录成功
            } else {
                return false; // 登录失败
            }
        } catch (PDOException $e) {
            echo "登录失败: " . $e->getMessage();
            return "登录失败";
        }
    }
    
    public function getUsersFile($creator_id) {// 查看用户拥有的文件
        try {
            $stmt = $this->pdo->prepare("SELECT * FROM files WHERE creator_id = :creator_id");
            $stmt->bindParam(':creator_id', $creator_id);
            $stmt->execute();

            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            echo "获取失败: " . $e->getMessage();
        }
    }

    public function insertUser($username, $password) {
        try {
            $stmt = $this->pdo->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
            $stmt->execute([$username, $password]);
            echo "插入成功";
        } catch (PDOException $e) {
            echo "插入失败: " . $e->getMessage();
        }
    }

    // 其他操作方法可以在此添加

    public function closeConnection() {
        $this->pdo = null;
    }
}
?>
